package com.android.xcalendar.activity;

import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.android.xcalendar.AlarmReceiver;
import com.android.xcalendar.C2DMRegistration;
import com.android.xcalendar.R;
import com.android.xcalendar.model.Event;
import com.android.xcalendar.util.XCalendarContentManager;
import com.android.xcalendar.view.CalendarView;
import com.android.xcalendar.view.Cell;

public class MonthViewActivity extends Activity implements
		CalendarView.OnCellTouchListener, OnClickListener {
	private CalendarView mView;
	private Button leftButton;
	private Button rightButton;
	private Button addLocationButton;
	private Button addEventButton;
	private TextView monthTextView;
//	private TextView text1;
	private MyReceiver receiver;
	public static final String SENDER_ID = "lixiaoyi.efrei@gmail.com";
	public static final String MESSAGE_KEY_ONE = "msg";
	XCalendarContentManager contentManager = XCalendarContentManager.getInstance();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.monthview);
		mView = (CalendarView) findViewById(R.id.calendar);
		leftButton = (Button) findViewById(R.id.calendar_left_button);
		rightButton = (Button) findViewById(R.id.calendar_right_button);
		addLocationButton = (Button) findViewById(R.id.button_add_location);
		addEventButton = (Button) findViewById(R.id.button_add_event);
		monthTextView = (TextView) findViewById(R.id.month);
//		text1 = (TextView)findViewById(R.id.text1);
		mView.setOnCellTouchListener(this);
		leftButton.setOnClickListener(this);
		rightButton.setOnClickListener(this);
		addLocationButton.setOnClickListener(newLocationListener);
		addEventButton.setOnClickListener(addEventListener);
		
		registerC2DM();

		mView.setData(contentManager.getDates());
		monthTextView.setText(monthConverter(mView.getMonth()));
		
		int i=0;
		for(Event event:contentManager.getEvents())
		{
			if(event.getRemindTime().getTime()>Calendar.getInstance().getTimeInMillis())
			{	i++;
				long alarmTime = event.getRemindTime().getTime();
				Log.d("remind",String.valueOf(alarmTime));
				
				Intent intent = new Intent(this, AlarmReceiver.class); 
				String strAlarm = event.getTitle().toString()+" from:"+
						event.getStartTime().toString()+" to:"+
						event.getEndTime().toString();
				intent.putExtra("strAlarm", strAlarm);
				PendingIntent pendingIntent = PendingIntent.getBroadcast(this, i, intent, 0);  
				AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);  
				alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); 

			}
		}
		Log.d("remind",String.valueOf(System.currentTimeMillis()));

	}

    
	private OnClickListener newLocationListener = new OnClickListener()
	{
		@Override
		public void onClick(View v) {
			Intent newIntent = new Intent(getApplicationContext(),NewLocationActivity.class);	
			startActivity(newIntent);
			
		}
	};
	
	private OnClickListener addEventListener = new OnClickListener()
	{
		@Override
		public void onClick(View v) {
			Intent newIntent = new Intent(getApplicationContext(),NewEventActivity.class);	
			startActivity(newIntent);
			
		}
		
	};

	public void onTouch(Cell cell) {
		if (!cell.isGrey()) {		
			contentManager.initDayView(mView.getYear(), mView.getMonth(), cell.getDayOfMonth());
			
			Intent newIntent = new Intent(getApplicationContext(),DayViewActivity.class);	
			startActivity(newIntent);
			
//			Toast.makeText(
//					this,
//					monthConverter(mView.getMonth()) + " - "
//							+ cell.getDayOfMonth(), Toast.LENGTH_SHORT).show();
		}
		else if(cell.getDayOfMonth()>15)
			onClick(leftButton);
		else 
			onClick(rightButton);
	}

	@Override
	public void onClick(View v) {
		Button vb = (Button) v;
		if (vb == leftButton) {
			mView.previousMonth();

		} else {
			mView.nextMonth();
		}
		monthTextView.setText(monthConverter(mView.getMonth()));
	}

	private String monthConverter(int month) {
		switch (month) {
		case 0:
			return "January";
		case 1:
			return "February";
		case 2:
			return "March";
		case 3:
			return "April";
		case 4:
			return "May";
		case 5:
			return "June";
		case 6:
			return "July";
		case 7:
			return "August";
		case 8:
			return "September";
		case 9:
			return "October";
		case 10:
			return "November";
		case 11:
			return "December";
		default:
			return "";
		}
	}
	private void registerC2DM() {
		/*if(C2DMRegistration.getRegistrationID(this).equals("")){
			Log.v("helo", "Register C2DM");
	        C2DMRegistration.register(this, SENDER_ID);
        }else {
        	Log.v("helo", "C2DM registered");
		}*/
		C2DMRegistration.register(this, SENDER_ID);
        receiver=new MyReceiver();
		IntentFilter filter=new IntentFilter();
		filter.addAction("android.intent.action.test");
		registerReceiver(receiver,filter);
	}
	public class MyReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String messageString = intent.getStringExtra("message");
			//text1.append(messageString);
			parseJsonText(messageString);
			mView.setData(contentManager.getDates());
		}
		public MyReceiver(){
			
		}
 
	}
	private void parseJsonText(String jsonText) {
		try {
			Log.d("num", contentManager.getDates().size()+"");
			JSONObject jsonObject = new JSONObject(jsonText);
			contentManager.parseEvents(jsonObject);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}
	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	}
	
}